/**
 * Reformer.com Inc.
 * Copyright (c) 2017-2022 All Rights Reserved.
 */
package com.reformer.commons.utils;

import com.reformer.commons.constant.RegExp;

/**
 * ip过滤器
 *
 * @author sdc
 * @version 1.0
 * @date 2017年6月26日
 * @since 1.0
 */
public class IPFilter {
    public static boolean filterWhiteList(String filterRule, String ip) {
        if (null == filterRule || null == ip) {
            return false;
        }
        if ("*".equals(filterRule)) {
            return true;
        }
        if (filterRule.trim().length() == 0) {
            return false;
        }
        if (!ip.matches(RegExp.IPV4)) {
            return false;
        }
        if (filterRule.equals(ip)) {
            return true;
        }
        if (filterRule.contains(",")) {
            String[] ips = filterRule.split(",");
            for (String e : ips) {
                if (e.equals(ip)) {
                    return true;
                }
            }
            return false;
        }
        if (filterRule.contains("/")) {
            String prefixRule = filterRule.substring(0, filterRule.lastIndexOf("."));
            String prefixIp = ip.substring(0, ip.lastIndexOf("."));
            if (!prefixRule.equals(prefixIp)) {
                return false;
            }
            String[] ranges = filterRule.substring(filterRule.lastIndexOf(".") + 1).split("/");
            int from = Integer.parseInt(ranges[0]);
            int to = Integer.parseInt(ranges[1]);
            int suffixIp = Integer.parseInt(ip.substring(ip.lastIndexOf(".") + 1));
            if (suffixIp >= from && suffixIp <= to) {
                return true;
            }
        }
        return false;
    }

//	public static void main(String[] args) {
//		System.out.println(filterWhiteList("*", "127.0.0.1"));
//		System.out.println(filterWhiteList("127.0.0.1,192.168.10.1", "127.0.0.1"));
//		System.out.println(filterWhiteList("127.0.0.1/20", "127.0.0.1"));
//		System.out.println(filterWhiteList("127.0.0.1/20", "127.0.0.21"));
//		System.out.println(filterWhiteList("127.0.0.1/20", "127.10.0.1"));
//	}
}
